package com.wujilin.okra.fragment;

import static android.app.Activity.RESULT_OK;
import static com.wujilin.okra.Okra.EXTRA_CATEGORY_NAME;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_CONTENT;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_GRADE;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_ID;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_TIME;
import static com.wujilin.okra.Okra.LOADER_KEY_RESULT_LIST;
import static com.wujilin.okra.Okra.LOADER_OBJECTIVE;
import static com.wujilin.okra.Okra.REQUEST_CATEGORY_CHOOSE;
import static com.wujilin.okra.Okra.REQUEST_CATEGORY_NEW;
import static com.wujilin.okra.Okra.REQUEST_KEY_RESULT_DELETE;
import static com.wujilin.okra.Okra.REQUEST_KEY_RESULT_EDIT;
import static com.wujilin.okra.Okra.REQUEST_KEY_RESULT_NEW;
import static com.wujilin.okra.Okra.REQUEST_OBJECTIVE_EDIT;
import static com.wujilin.okra.Okra.TAG_DIALOG_CATEGORY_CHOOSE;
import static com.wujilin.okra.Okra.TAG_DIALOG_KEY_RESULT_DELETE;
import static com.wujilin.okra.Okra.TAG_DIALOG_KEY_RESULT_EDIT;
import static com.wujilin.okra.Okra.TAG_DIALOG_KEY_RESULT_NEW;
import static com.wujilin.okra.Okra.TAG_DIALOG_OBJECTIVE_EDIT;
import static com.wujilin.okra.Okra.TAG_DIALOG_OKRA_DELETE;
import static com.wujilin.okra.Okra.T_KEY_RESULT;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.wujilin.okra.R;
import com.wujilin.okra.adapter.KeyResultListAdapter;
import com.wujilin.okra.database.ModelCursor;
import com.wujilin.okra.loader.ModelQueryLoader;
import com.wujilin.okra.loader.SelectCursorLoader;
import com.wujilin.okra.model.Model;

public class OkraFragment extends Fragment implements OnItemClickListener, LoaderCallbacks<Cursor> {
	private TextView objectiveText;
	private TextView quarterText;
	private TextView objectiveTime;
	private TextView objectiveGrade;
	private TextView objectiveCategory;
	private TextView countText;
	private ListView keyResults;
	
	private long objectiveId;
	private long categoryId = -1; // Unknow category
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		
		objectiveId = getArguments().getLong(EXTRA_OBJECTIVE_ID);
		
		LoaderManager loaderManager = getLoaderManager();
		loaderManager.initLoader(LOADER_OBJECTIVE, null, objectiveLoaderCallbacks);
		loaderManager.initLoader(LOADER_KEY_RESULT_LIST, null, this);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_okra, menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				getActivity().finish();
				break;
			case R.id.new_key_result: {
				KeyResultNewFragment fragment = KeyResultNewFragment.newInstance(objectiveId);
				fragment.show(getFragmentManager(), TAG_DIALOG_KEY_RESULT_NEW);
				fragment.setTargetFragment(OkraFragment.this, REQUEST_KEY_RESULT_NEW);
				break;
			}
			case R.id.move_to:
				if (categoryId != -1) {
					CategoryChooseFragment fragment = CategoryChooseFragment.newInstance(objectiveId, categoryId);
					fragment.setTargetFragment(this, REQUEST_CATEGORY_CHOOSE);
					fragment.show(getFragmentManager(), TAG_DIALOG_CATEGORY_CHOOSE);
				}
				break;
			case R.id.delete:
				OkraDeleteFragment okraDeleteFragment = OkraDeleteFragment.newInstance(objectiveId);
				okraDeleteFragment.show(getFragmentManager(), TAG_DIALOG_OKRA_DELETE);
				break;
			default:
				return false;
		}
		return true;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		getActivity().getMenuInflater().inflate(R.menu.fragment_okra_context, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		long keyResultId = info.id;
		
		switch (item.getItemId()) {
		case R.id.delete:
			KeyResultDeleteFragment fragment = KeyResultDeleteFragment.netInstance(keyResultId);
			fragment.setTargetFragment(this, REQUEST_KEY_RESULT_DELETE);
			fragment.show(getFragmentManager(), TAG_DIALOG_KEY_RESULT_DELETE);
			break;
		}
		return true;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_okra, container, false);
		findViews(view);
		initViews();
		return view;
	}

	private void findViews(View view) {
		objectiveText = (TextView) view.findViewById(R.id.objective_content);
		objectiveTime = (TextView) view.findViewById(R.id.objective_time);
		objectiveGrade = (TextView) view.findViewById(R.id.objective_grade);
		objectiveCategory = (TextView) view.findViewById(R.id.objective_category);
		quarterText = (TextView) view.findViewById(R.id.objective_quarter);
		countText = (TextView) view.findViewById(R.id.count);
		keyResults = (ListView) view.findViewById(R.id.list_key_result);
		
		registerForContextMenu(keyResults);
	}
	
	private void initViews() {
		objectiveText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = objectiveText.getText().toString();
				ObjectiveEditFragment fragment = ObjectiveEditFragment.newInstance(objectiveId, content);
				fragment.setTargetFragment(OkraFragment.this, REQUEST_OBJECTIVE_EDIT);
				fragment.show(getFragmentManager(), TAG_DIALOG_OBJECTIVE_EDIT);
			}
		});
		keyResults.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		TextView contentText = (TextView) view.findViewById(R.id.key_result_content);
		TextView gradeText = (TextView) view.findViewById(R.id.grade);
		String content = contentText.getText().toString();
		double grade = Double.valueOf(gradeText.getText().toString());
		KeyResultEditFragment fragment = KeyResultEditFragment.newInstance(id, content, grade, objectiveId);
		fragment.show(getFragmentManager(), TAG_DIALOG_KEY_RESULT_EDIT);
		fragment.setTargetFragment(this, REQUEST_KEY_RESULT_EDIT);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case REQUEST_OBJECTIVE_EDIT:
				if (resultCode == RESULT_OK) {
					String content = data.getStringExtra(EXTRA_OBJECTIVE_CONTENT);
					String time = data.getStringExtra(EXTRA_OBJECTIVE_TIME);
					objectiveText.setText(content);
					objectiveTime.setText(time);
				}
				break;
			case REQUEST_KEY_RESULT_NEW:
			case REQUEST_KEY_RESULT_EDIT:
			case REQUEST_KEY_RESULT_DELETE:
				if (resultCode == RESULT_OK) {
					String grade = data.getStringExtra(EXTRA_OBJECTIVE_GRADE);
					String objTime = data.getStringExtra(EXTRA_OBJECTIVE_TIME);
					objectiveTime.setText(objTime);
					objectiveGrade.setText(grade);
					getLoaderManager().restartLoader(LOADER_KEY_RESULT_LIST, null, this);
				}
				break;
			case REQUEST_CATEGORY_NEW:
			case REQUEST_CATEGORY_CHOOSE:
				if (resultCode == RESULT_OK) {
					String category = data.getStringExtra(EXTRA_CATEGORY_NAME);
					objectiveCategory.setText(category);
				}
				break;
		}
	}
	
	public static OkraFragment newInstance(long id) {
		Bundle args = new Bundle(1);
		args.putLong(EXTRA_OBJECTIVE_ID, id);
		
		OkraFragment fragment = new OkraFragment();
		fragment.setArguments(args);
		
		return fragment;
	}
	
	private LoaderCallbacks<Model> objectiveLoaderCallbacks = new LoaderCallbacks<Model>() {
		@Override
		public void onLoaderReset(Loader<Model> loader) {
		}
		
		@Override
		public void onLoadFinished(Loader<Model> loader, Model objective) {
			categoryId = objective.getInteger("category_id");
			objectiveText.setText(objective.getString("content"));
			quarterText.setText(objective.getString("year") + "/Q" + objective.getString("quarter"));
			objectiveTime.setText(objective.getString("time"));
			objectiveGrade.setText(objective.getString("grade"));
			objectiveCategory.setText(objective.getString("category"));
		}
		
		@Override
		public Loader<Model> onCreateLoader(int id, Bundle args) {
			String sql = "select o.*,c.name category from objective o left join category c on o.category_id=c._id where o._id=?";
			return new ModelQueryLoader(getActivity(), sql, objectiveId + "");
		}
	};

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Loader<Cursor> loader = new SelectCursorLoader.Builder(getActivity(), T_KEY_RESULT)
			.selection("objective_id=?")
			.selectionArgs(objectiveId + "")
			.build();
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		countText.setText(data.getCount() + "");
		keyResults.setAdapter(new KeyResultListAdapter(getActivity(), (ModelCursor) data));
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		keyResults.setAdapter(null);
	}
}
